package com.denlaku.longan.handlers;

import com.denlaku.longan.util.JsonUtil;
import com.denlaku.longan.util.Lists;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author tianx
 */
public class ObjectListTypeHandler extends BaseTypeHandler<List<Object>> {
    private final static TypeReference<List<Object>> TYPE_REFERENCE = new TypeReference<List<Object>>(){};

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Object> list, JdbcType jdbcType)
            throws SQLException {
        if (list != null) {
            ps.setObject(i, JsonUtil.toJsonString(list));
        }
    }

    @Override
    public List<Object> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return parseObject(json);
    }

    @Override
    public List<Object> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return parseObject(json);
    }

    @Override
    public List<Object> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return parseObject(json);
    }

    private List<Object> parseObject(String json) {
        if (StringUtils.isEmpty(json)) {
            return Lists.empty();
        }
        return JsonUtil.parseObject(json, TYPE_REFERENCE);
    }

}
